﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Drawing.Drawing2D;
using System.IO;
using WhiteBoard;
using System.Runtime.InteropServices;

namespace WFFS
{
    public partial class FrmAlldirective : Form
    {
        private Form1 frmMain = null;
        DShapeList drawingList = new DShapeList();							//图元
        DShapeList drawingListUndo = new DShapeList();						//撤销图形保存
        //临时变量
        private GraphicsPath mousePath;
        Point startPoint, endPoint; //开始画线的起点坐标，此变量的值将在MOUSEDOWN事件中确定 
        public Color drawColor = Color.FromArgb(0, 0, 0);//选择的颜色
        public int lineWidth = 4;//线宽度
        public ImageType newType = ImageType.Path;
        NewForm newForm = new NewForm();
        public Button selectButton;//被选中的图标
        public Image memory;//切图临时保存
        public FrmAlldirective(Form1 _frm)
        {
            InitializeComponent();
            frmMain = _frm;
            initForm();

        }
        //表单初始化
        public void initForm()
        {
            this.Drawing.Paint += new System.Windows.Forms.PaintEventHandler(this.Drawing_Paint);
            //控件要能拖动必须设置控件的AllowDrop=true
            this.Drawing.AllowDrop = true;
            // 这句代码就是说在这个类中我们不检查跨线程的调用是否合法
            Control.CheckForIllegalCrossThreadCalls = false;
                //画图
                this.Drawing.MouseDown += new MouseEventHandler(Drawing_MouseDown);
                this.Drawing.MouseMove += new MouseEventHandler(Drawing_MouseMove);
                this.Drawing.MouseUp += new MouseEventHandler(Drawing_MouseUp);
                //拖拽
                this.Drawing.DragDrop += new System.Windows.Forms.DragEventHandler(this.Drawing_DragDrop);
                this.Drawing.DragEnter += new System.Windows.Forms.DragEventHandler(this.Drawing_DragEnter);
        }
        private void font_Click(object sender, EventArgs e){
            this.newType = ImageType.Text;
        }
          private void line_Click(object sender, EventArgs e){
              this.newType = ImageType.Path;
        }
        
        /// <summary>
        /// 画图事件
        /// </summary>		
        private void Drawing_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == System.Windows.Forms.MouseButtons.Left){
                WhenMouseDown(new Point(e.X, e.Y));
            }
        }
        private void Drawing_MouseMove(object sender, MouseEventArgs e)
        {
            if (e.Button == System.Windows.Forms.MouseButtons.Left)
            {
                switch (newType)
                {
                    case ImageType.Path:
                        WhenMouseMove(new Point(e.X, e.Y));
                        break;
                }

            }
        }
        private void Drawing_MouseUp(object sender, MouseEventArgs e)
        {
            switch (newType)
            {
                case ImageType.Path:
                    WhenMouseUp(new Point(e.X, e.Y));
                    break;
            }

        }
        private void Drawing_Paint(object sender, System.Windows.Forms.PaintEventArgs e)
        {
            Graphics displayGraphics = e.Graphics;
            //Graphics displayGraphics=this.Drawing.CreateGraphics();
            switch (newType)
            {
                case ImageType.Path:
                    if (mousePath != null)
                    {
                        displayGraphics.DrawPath(new Pen(drawColor, lineWidth), mousePath);
                    }
                    break;
                case ImageType.Pick:
                    break;
            }
            drawingList.DrawList(displayGraphics);
        }
        //画图，当鼠标按下
        public void WhenMouseDown(Point pt) {
          startPoint = pt;
           switch (newType)
            {
                case ImageType.Path:
                    //鼠标按下确定起点的坐标，把这个变量赋于startPoint值 
                    mousePath = new GraphicsPath();
                    mousePath.AddLine(pt, pt);
                    break;
                case ImageType.Text:
                   	newForm.Show();
                    newForm.Location = new Point(300, 400);
                    newForm.VisibleChanged += new EventHandler(newForm_VisibleChanged); 
					break;
            }
        }
        private void newForm_VisibleChanged(object sender, System.EventArgs e)
        {
            if (newForm.Visible == false){
                switch (newType)
                {
                    case ImageType.Text:
                        if (newForm.cancle == false)
                        {
                            drawingList.Add(new DText(new Point[] { startPoint }, this.drawColor, newForm.outText, newForm.txtSize, newForm.TxtFont));
                            Drawing.Invalidate();
                        }
                        break;
                }
            }
        }
        //画图，当鼠标移动
        public void WhenMouseMove(Point pt)
        {
            switch (newType)
            {
                case ImageType.Path:
                    mousePath.AddLine(pt, pt);
                    break;
            }
            Drawing.Invalidate();
        }
        //画图，当鼠标抬起
        public void WhenMouseUp(Point pt)
        {
            endPoint = pt;
            switch (newType)
            {
                case ImageType.Path:
                    drawingList.Add(new DPath(mousePath, drawColor, lineWidth));
                    mousePath = null;
                    break;
            }
          
        }

        /// <summary>
        /// 后退
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void back_Click(object sender, EventArgs e)
        {
            WhenBack();
          
        }
        /// <summary>
        /// 前进
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void proceed_Click(object sender, EventArgs e)
        {
            WhenProceed();
         
        }
     
        //画图，撤消
        public void WhenBack()
        {
            if (drawingList.Count == 0)
                return;
            drawingListUndo.Add(drawingList[drawingList.Count - 1]);
            drawingList.RemoveAt(drawingList.Count - 1);
            Drawing.Invalidate();
        }
        //画图，恢复
        public void WhenProceed()
        {
            if (drawingListUndo.Count == 0)
                return;
            drawingList.Add(drawingListUndo[drawingListUndo.Count - 1]);
            drawingListUndo.RemoveAt(drawingListUndo.Count - 1);
            Drawing.Invalidate();
        }

        //清除
        private void clearScreen(object sender, EventArgs e)
        {
            this.clearScreen();
           
        }
        //删除图标
        private void deleteButton(object sender, EventArgs e)
        {
            if (this.selectButton != null)
            {
                this.Drawing.Controls.Remove(selectButton);
            }
        }

        //清除显示
        public void clearScreen()
        {
            drawingList = new DShapeList();
            drawingListUndo = new DShapeList();
            //清除控件           
            List<Control> list = new List<Control>();
            foreach (Control Item in this.Drawing.Controls)
            {
                list.Add(Item);
            }
            int size = this.Drawing.Controls.Count;
            for (int i = 0; i < size; i++)
            {
                this.Drawing.Controls.Remove(list[i]);
            }
            Drawing.Invalidate();
        }
        //设置线的宽度
        private void setlineWidth(object sender, EventArgs e) {

            ToolStripDropDownItem buton = (ToolStripDropDownItem)sender;
            lineWidth = int.Parse(buton.Text);
        }
        //设置颜色
        private void color_Click(object sender, System.EventArgs e){
            ToolStripDropDownItem buton = (ToolStripDropDownItem)sender; //xiaojun            
            System.Drawing.ColorConverter cc = new ColorConverter();
            drawColor = (Color)cc.ConvertFromString(buton.Name);
        }

      

        //更多
        private void MoreColor_Click(object sender, System.EventArgs e)
        {
            if (colorDialog.ShowDialog() == DialogResult.OK)
            {
                drawColor = colorDialog.Color;
            }
        }

      
        //图片按下事件
        private void imageDrafting_MouseDown(object sender, MouseEventArgs e)
        {
            newType = ImageType.carDrafting;
           // ToolStripButton buton = (ToolStripButton)sender;
            ToolStripDropDownItem buton = (ToolStripDropDownItem)sender; //xiaojun
            UiDrafting_MouseDown(buton.Name, "imgOrder");
        }
        /////////////////////////////////////////////控件拖动<将控件拖动到另一个容器内>//////////////////////////////////////////////////

        private void Drawing_DragDrop(object sender, DragEventArgs e)
        {
            if (newType == ImageType.carDrafting)
            {
                Control control = (Control)sender;
                String text = e.Data.GetData(DataFormats.Text).ToString();
                Point p = control.PointToClient(Control.MousePosition); //点P是相对于画图控件坐标
                Random ran = new Random();
                int RandKey = ran.Next(100, 999);
                string name = "bushu" + RandKey;
                UiDraftingControl_DragDrop(name, text, p);
            }
        }
        private void Drawing_DragEnter(object sender, DragEventArgs e)
        {
            if (newType == ImageType.carDrafting)
            {
                UiDraftingControl_DragEnter(e);
            }
        }


        //拖放事件
        //名称 说明
        //DragEnter 当用户在拖放操作过程中首次将鼠标光标拖到控件上时，会引发该事件
        //DragDrop 在完成拖放操作时发生
        //GiveFeedback 在执行拖动操作期间发生
        //DragLeave 如果用户移出一个窗口，则引发DragLeave事件
        //DragOver 如果鼠标移动但停留在同一个控件中，则引发DragOver事件
        //QueryContinueDrag 在拖放操作过程中，当键盘或鼠标按钮状态发生变化时，会引发QueryContinueDrag 事件。QueryContinueDrag事件允许拖动源确定是否应取消拖放操作

        //要拖动的控件的 MouseDown事件
        public void UiDrafting_MouseDown(String title, String type)
        {
            this.h.DoDragDrop(title + "," + type, DragDropEffects.Copy);
            /**
           public DragDropEffects DoDragDrop ( Object sender,DragDropEffects allowedEffects)
           data：用户所要拖动的数据内容。必须将所要拖动的内容传入到这个方法的第一个参数位置。
           allowedEffects：DragDropEffects枚举值之一，此类型包含了拖动操作的效果。DragDropEffects枚举值如表32.8所示。
           DragDropEffects枚举值：
             枚举值 说明
             All 从拖动源复制、移除数据，并将其滚动到放置目标中
             Copy 将数据复制到放置目标
             Link 将拖动源中的数据链接到放置目标
             Move 将拖动源的数据移动到放置目标
             None 放置目标不接受该数据
             Scroll 即将在放置目标中开始滚动，或当前正在滚动
           开发人员在使用DoDragDrop方法时，必须指定参数allowedEffects为表中的任何一个成员，另外，还可以使用位运算符，把其中的任何一个成员作为一个完整参数传入，以得到所需的拖动效果，实现关键代码如下：
             DragDropEffects.Copy| DragDropEffects.None**/
        }
        //控件拖动到控件的 DragEnter事件
        public void UiDraftingControl_DragEnter(DragEventArgs e)
        {
            e.Effect = DragDropEffects.Copy;
        }


        //声明委托类型
        public delegate void InvokeDele(String name, String text, Point p);
        //控件拖动到控件的 DragDrop事件
        public void UiDraftingControl_DragDrop(String name, String text, Point p)
        {
            //跨线程的控件操作，需要使用委托
            if (this.InvokeRequired)
            {
                //实例化委托
                InvokeDele id = new InvokeDele(this.UiDraftingControl_DragDrop);
                this.Invoke(id, new object[] { name, text, p });
                return;
            }
            Control control = this.Drawing;
            // 取得被拖放的项       
            Button tuttontemp = new Button();
            tuttontemp.Name = name;
            tuttontemp.TextAlign = ContentAlignment.BottomCenter;
            tuttontemp.BackgroundImageLayout = ImageLayout.Center;
            if ((text.Split(','))[1].Equals("car"))
            {//车辆
                tuttontemp.BackgroundImage = new Bitmap(Application.StartupPath + "\\bushutu\\car3.png");
                tuttontemp.Text = (text.Split(','))[0];
            }
            else if ((text.Split(','))[1].Equals("duanhao"))
            {//段号
                String[] tishi = text.Split(',')[0].Split(';');
                tuttontemp.BackgroundImage = new Bitmap(Application.StartupPath + "\\bushutu\\d" + tishi[0] + ".png");
                tuttontemp.Text = tishi[1] + ":" + tishi[2];
            }
            else if ((text.Split(','))[1].Equals("imgOrder"))
            {//图标命令
                tuttontemp.BackgroundImage = new Bitmap(Application.StartupPath + "\\bushutu\\" + (text.Split(','))[0] + ".png");
            }
            else
            {//人员
                tuttontemp.BackgroundImage = new Bitmap(Application.StartupPath + "\\bushutu\\001.png");
                tuttontemp.Text = (text.Split(','))[0];
            }
            tuttontemp.Location = p;
            control.Controls.Add(tuttontemp);
            Size size = tuttontemp.BackgroundImage.Size;
            size.Width = size.Width + 7;
            size.Height = size.Height + 7;
            tuttontemp.Size = size;
            tuttontemp.AllowDrop = true;
            tuttontemp.MouseDown += new MouseEventHandler(UiMove_MouseDown);
            tuttontemp.MouseMove += new MouseEventHandler(UiMove_MouseMove);
            tuttontemp.MouseUp += new MouseEventHandler(UiMove_MouseUp);
            this.selectButton = tuttontemp;
           
        }
        /////////////////////////////////////////////控件移动<控件在对应的容器内移动>//////////////////////////////////////////////////
        bool bDragging = false;//是否移动的变量
        Point mouse_offset;//开始位置
        private void UiMove_MouseDown(object sender, MouseEventArgs e)
        {
            this.selectButton = ((Button)sender);
            whenUiMove_MouseDown(new Point(-e.X, -e.Y));

        }
        public void whenUiMove_MouseDown(Point p)
        {
            bDragging = true;
            mouse_offset = p;
        }
        private void UiMove_MouseMove(object sender, MouseEventArgs e)
        {
            String name = ((Control)sender).Name;
            //设置拖动时鼠标箭头
            ((Control)sender).Cursor = Cursors.Arrow;
            whenUiMove_MouseMove(name, e.Button, Control.MousePosition);
        }
        public void whenUiMove_MouseMove(String name, MouseButtons button, Point mousePos)
        {
            if (button == MouseButtons.Left && bDragging)
            {
                mousePos.Offset(mouse_offset.X, mouse_offset.Y);//设置偏移
                Control control = GetControl(name, this.Drawing);
                if (control == null) return;
                control.Location = control.Parent.PointToClient(mousePos);
            }
        }
        //根据名字得到控件
        private Control GetControl(string name, Control parent)
        {
            foreach (Control Item in parent.Controls)
            {
                if (Item.Name == name)
                {
                    return Item;
                }
                else
                {
                    Control control = GetControl(name, Item);
                    if (control != null)
                    {
                        return control;
                    }
                }
            }
            return null;
        }
        private void UiMove_MouseUp(object sender, MouseEventArgs e)
        {
            whenUiMove_MouseUp();
        }
        public void whenUiMove_MouseUp()
        {
            bDragging = false;
        }
        //设置背景
        private void catimage_Click(object sender, EventArgs e){
            this.Hide();
            System.Threading.Thread.Sleep(1000);
            Image img = new Bitmap(Screen.AllScreens[0].Bounds.Width, Screen.AllScreens[0].Bounds.Height);
            Graphics g = Graphics.FromImage(img);
            g.CopyFromScreen(new Point(0, 0), new Point(0, 0), Screen.AllScreens[0].Bounds.Size);
            ScreenBody body = new ScreenBody(this,"Alldirective");//5+1+a+s+p+x
            body.BackgroundImage = img;
            body.Show();
        }
      
        //生成图片
        public WBMsgAllDirective createImage() {
            Bitmap bit = new Bitmap(Drawing.Width, Drawing.Height);
            Drawing.DrawToBitmap(bit, Drawing.ClientRectangle);
            MemoryStream ms = new MemoryStream();
                bit.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
                byte[] bytes = ms.GetBuffer();
                WBMsgAllDirective wn = new WBMsgAllDirective();
                wn.im = bytes;
                String name = DateTime.Now.ToString("yyyyMMddHHmmss") + ".bmp";
                wn.name = name;
                //保存图片到服务器
                frmMain.whenAlldirective(bytes, name);
                bit.Dispose();
                return wn;
           
        }
        FrmSendAlldirective frmSendAlldirective;
        private void toolStripButton7_Click(object sender, EventArgs e)
        {

            if (frmSendAlldirective != null) {
                frmSendAlldirective.Dispose();
                frmSendAlldirective = null;
              
            }
            frmSendAlldirective = new FrmSendAlldirective(frmMain, this);
            frmSendAlldirective.Show();
            string x = ReadIniData("FrmSendAlldirective", "X", "X", Application.StartupPath + @"\WFFS.ini");
            string y = ReadIniData("FrmSendAlldirective", "Y", "Y", Application.StartupPath + @"\WFFS.ini");
            frmSendAlldirective.Location = new Point(int.Parse(x), int.Parse(y));
            frmSendAlldirective.TopMost = true;
            
        }
        /// <summary>
        /// 读取ini文件
        /// </summary>
        /// <param name="Section">段落</param>
        /// <param name="Key">关键字</param>
        /// <param name="NoText">关键字对应的值</param>
        /// <param name="iniFilePath">文件路径</param>
        /// <returns></returns>
        public static string ReadIniData(string Section, string Key, string NoText, string iniFilePath)
        {
            if (File.Exists(iniFilePath))
            {
                StringBuilder temp = new StringBuilder(1024);
                GetPrivateProfileString(Section, Key, NoText, temp, 1024, iniFilePath);
                return temp.ToString();
            }
            else
            {
                return String.Empty;
            }
        }
        [DllImport("kernel32")]
        private static extern long GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath);

        private void FrmAlldirective_FormClosed(object sender, FormClosedEventArgs e)
        {
            string x = this.Location.X.ToString();
            string y = this.Location.Y.ToString();
            WriteIniData("FrmAlldirective", "X", x, Application.StartupPath + @"\WFFS.ini");
            WriteIniData("FrmAlldirective", "Y", y, Application.StartupPath + @"\WFFS.ini");
        }

        public static bool WriteIniData(string Section, string Key, string Value, string iniFilePath)
        {
            if (File.Exists(iniFilePath))
            {
                long OpStation = WritePrivateProfileString(Section, Key, Value, iniFilePath);
                if (OpStation == 0)
                {
                    return false;
                }
                else
                {
                    return true;
                }
            }
            else
            {
                return false;
            }
        }
        [DllImport("kernel32")]
        private static extern long WritePrivateProfileString(string section, string key, string val, string filePath);
        //窗口大小改变
        private void FrmAlldirective_SizeChanged(object sender, EventArgs e){
            Drawing.Image = Util.update_Size(memory,Drawing.Width, Drawing.Height);
        }
    }
}
